package cn.school.telephone.service.impl;

import cn.school.common.utils.SysUserUtils;
import cn.school.sys.service.SysConfigService;
import cn.school.telephone.bean.addmodify.TelephoneReqDto;
import cn.school.telephone.bean.addmodify.TelephoneResp;
import cn.school.telephone.bean.addmodify.TelephoneResponse;
import cn.school.telephone.bean.get.GetResponse;
import cn.school.telephone.bean.get.ParamEntity;
import cn.school.telephone.bean.get.SyncUserInfoEntity;
import cn.school.telephone.bean.get.Viso;
import cn.school.telephone.service.TelephoneService;
import cn.school.telephone.utils.Md5TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class TelephoneServiceImpl implements TelephoneService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SysConfigService sysConfigService;

    // 同步学生信息到话机
    public TelephoneResponse syncBatchUserFaceImageByUrl(TelephoneReqDto telephoneReqDto) {

        String[] phoneArr = sysConfigService.getValueByKey("public.telephone.param").getParamValue().split("-");
        telephoneReqDto.getReqEntity().setSchId(phoneArr[0]);  // 公话学校id
        HttpHeaders headers = getToken(phoneArr[1], phoneArr[2]);
        TelephoneResponse telephoneResponse = null;
        try {
            HttpEntity<TelephoneReqDto> entity = new HttpEntity(telephoneReqDto, headers);
            telephoneResponse = restTemplate.postForObject("https://smsh.shomr.com/gateSchInOutServer/VideoPhoneOutUnion/syncBatchUserFaceImageByUrl",
                    entity, TelephoneResponse.class);

            for (TelephoneResp telephoneResp : telephoneResponse.getResEntity().getList()) {
                if (!telephoneResp.isOk()) {
                    log.error("同步信息失败! 学生id ==>  {} ， 学生名称 ==> {}", telephoneResp.getUserId(), telephoneResp.getUserName());
                }
            }
            log.info("结果 ===> {} ,   message ==> {}", telephoneResponse.getCode(), telephoneResponse.getMessage());
        } catch (RestClientException e) {
            log.error(e.getMessage());
        }
        return telephoneResponse;
    }

    @Override
    public Map<String, Object> syncDelSomeUserByAllUser(String schId, List<String> studentIds) {
        // 系统参数中查出话机学校id,key,公话秘钥
        String[] phoneArr = sysConfigService.getValueByKey("public.telephone.param").getParamValue().split("-");
        HttpHeaders headers = getToken(phoneArr[1], phoneArr[2]);
        Map<String, Object> outerMap = new HashMap<>();
        Map<String, Object> innerMap = new HashMap<>();
        innerMap.put("schId", phoneArr[0]);
        innerMap.put("cardNumbers", studentIds);
        outerMap.put("paramEntity", innerMap);

        HttpEntity<TelephoneReqDto> entity = new HttpEntity(outerMap, headers);

        Map map = restTemplate.postForObject("https://smsh.shomr.com/gateSchInOutServer/VideoPhoneOutUnion/syncDelSomeUser",
                entity, Map.class);
        return map;
    }

    // 获取话机内的学生信息
    @Override
    public List<SyncUserInfoEntity> getPhoneStudent() {
        Integer pageNo = 1;
        Integer pageSize = 1000;
        GetResponse getResponse = getUserInfo(pageNo, pageSize);
        List<SyncUserInfoEntity> list = new ArrayList<>();
        list.addAll(getResponse.getResEntity().getViso().getList());
        for (int i = 2; i <= getResponse.getResEntity().getViso().getTotalPages(); i++) {
            getResponse = getUserInfo(++pageNo, pageSize);
            list.addAll(getResponse.getResEntity().getViso().getList());
        }
        list = list.stream().filter(item -> "1".equals(item.getStatus())).collect(Collectors.toList());
        return list;
    }

    private GetResponse getUserInfo(Integer pageNo, Integer pageSize) {
        String[] phoneArr = sysConfigService.getValueByKey("public.telephone.param").getParamValue().split("-");
        ParamEntity paramEntity = new ParamEntity();
        paramEntity.setSchId(Integer.valueOf(phoneArr[0]));
        paramEntity.setViso(new Viso(pageNo, pageSize));

        HttpHeaders headers = getToken(phoneArr[1], phoneArr[2]);
        Map<String, ParamEntity> map = new HashMap<>();
        map.put("paramEntity", paramEntity);
        HttpEntity<Map<String, ParamEntity>> entity = new HttpEntity(map, headers);
        GetResponse getResponse = restTemplate.postForObject("https://smsh.shomr.com/gateSchInOutServer/VideoPhoneOutUnion/getUserInfoByViso",
                entity, GetResponse.class);
        return getResponse;
    }

    private HttpHeaders getToken(String agentId, String slat) {
        HttpHeaders headers = new HttpHeaders();
        String token = Md5TokenUtil.getMd5Token(agentId, slat);
        headers.add("token", token); // 添加所需的Header
        headers.add("Content-Type", "application/json;charset=utf-8");
        return headers;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(Md5TokenUtil.getMd5Token("110", "xYgQcEs20231106,+"));
//        System.out.println(Md5TokenUtil.getMd5Token("127", "zNsGS20240402,+aASign"));

        String encodedFileName = URLEncoder.encode("曾珊珊.jpg", "UTF-8");
        String encodedFileName2 = URLEncoder.encode("/2024-03-13/lxwzc2021116/曾珊珊.jpg", "UTF-8");
//        String url1 = url2.substring(0, url2.lastIndexOf('/') + 1) + encodedFileName;
        System.out.println("URL1: " + encodedFileName);
        System.out.println("URL1: " + encodedFileName2);
    }
}
